package com.koron.car.web.applycar.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.Response;
import com.koron.bean.query.OrderItem;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.bean.workflow.RedirectQuery;
import com.koron.bean.workflow.SubmitterParam;
import com.koron.bean.workflow.WorkflowController;
import com.koron.bean.workflow.WorkflowUser;
import com.koron.car.web.applycar.bean.entity.DriverRecord;
import com.koron.car.web.applycar.bean.query.CarApplyQuery;
import com.koron.car.web.applycar.bean.vo.CarApplyVO;
import com.koron.car.web.applycar.filter.CarApplyFilter;
import com.koron.car.web.applycar.service.CarApplyService;
import com.koron.common.core.annocation.CasUser;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.interceptor.OrderByInterceptor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;

/**
 * @author twcao
 * @title: CarApplyController
 * @projectName GDH_EAM_V2
 * @description: 用车申请接口controller
 * @date 2022/3/914:12
 */
@Slf4j
@RestController
@RequestMapping("/car/apply")
@Api(tags = "车辆管理-用车申请")
public class CarApplyController implements WorkflowController {

    @Autowired
    private CarApplyService carApplyService;

    @Autowired
    private CarApplyFilter filter;

    @GetMapping("/selectOne")
    @ApiOperation("根据申请id查询申请信息")
    @ApiImplicitParam(name = "applyId", value = "申请单id", required = true)
    public Response<CarApplyVO> selectOne(String applyId) {
        log.info("根据申请id查询申请信息， applyId = {}", applyId);
        CarApplyVO bean = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), carApplyService, "queryById", CarApplyVO.class, applyId);
        return Response.ok(bean);
    }

    @GetMapping("/queryList")
    @ApiOperation("根据条件查询用车申请列表")
    public Response<PageInfo<CarApplyVO>> queryList(CarApplyQuery query) {
        log.info("根据条件查询用车申请列表， query = {}", JSON.toJSONString(query));
        List <OrderItem> list = filterOrderItem(query.getOrders());
        OrderByInterceptor.setOrderBy(list);
        PageHelper.startPage(query.getPage(), query.getPageSize());
        List<CarApplyVO> beans2 = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), carApplyService, "queryList", List.class, query);
        PageInfo<CarApplyVO> pageInfo = new PageInfo<>(beans2);
        pageInfo.setList(beans2);
        return Response.ok(pageInfo);
    }

    /**
     * 过滤 Unknown column 'XXXXX' in 'order clause'
     * @param orders
     * @return
     */
    private List<OrderItem> filterOrderItem(List<OrderItem> orders) {
        List<OrderItem> list = new ArrayList<>();
        for (OrderItem order : orders) {
            if (order.getColumn().equals("`entourage`") || order.getColumn().equals("`driver_line`")) {
                continue;
            }
            if ( order.getColumn().equals("`driver_time`")){
                order.setColumn("startTime");
            }
            list.add(order);
        }
        return list;
    }

    @GetMapping("/scanCar")
    @ApiOperation("扫描车辆二维码，根据车牌号或者车辆id查询申请信息, 至少有一个不为空，同时不为空时，以车辆id为主")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "licPlateNum", value = "车牌号"),
            @ApiImplicitParam(name = "carId", value = "车辆id")
    })
    public Response<List<CarApplyVO>> scanCar(String licPlateNum, String carId) {
        log.info("扫描车辆二维码， licPlateNum = {}, carId = {}", licPlateNum, carId);
        List<CarApplyVO> bean = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), carApplyService, "scanCar", List.class, licPlateNum, carId);
        return Response.ok(bean);
    }

    @PostMapping("/saveOrUpdate")
    @ApiOperation("创建/更新用车申请单")
    public Response<CarApplyVO> saveOrUpdate(@RequestBody CarApplyVO carApply) {
        log.info("创建/更新用车申请单， carApply = {}", JSON.toJSONString(carApply));
        if(carApply.getRecordType() == null){
            carApply.setRecordType(0);
        }
        CarApplyVO bean = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), carApplyService, StringUtils.isBlank(carApply.getId()) ? "insert" : "update", CarApplyVO.class, carApply);
        return Response.ok(bean);
    }

    @GetMapping("/submit")
    @ApiOperation("提交用车申请")
    @ApiImplicitParam(name = "applyId", value = "申请单id", required = true)
    public Response<CarApplyVO> submit(String applyId) {
        log.info("提交用车申请， applyId = {}", applyId);
        CarApplyVO bean = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), carApplyService, "submit", CarApplyVO.class, applyId);
        return Response.ok(bean);
    }

    @GetMapping("/deleteById")
    @ApiOperation("根据申请id删除用车申请")
    @ApiImplicitParam(name = "applyId", value = "申请id", required = true)
    public Response<String> deleteById(@CasUser @ApiIgnore EamUser user, @RequestParam String applyId) {
        ADOConnection.runTask(user.getCurrDs(), carApplyService, "deleteById", Boolean.class, applyId);
        return Response.ok("删除成功", applyId);
    }

    @Override
    @ApiOperation("修改业务状态, 非前端接口")
    public Response<Object> updateState(@RequestBody RedirectQuery redirectQuery) {
        log.info("工作流更新： {}", JSON.toJSONString(redirectQuery));
        ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), carApplyService, "workflowUpdate", Boolean.class, redirectQuery);
        return Response.success();
    }

    @Override
    @ApiOperation("结束时的修改方法, 非前端接口")
    public Response<Object> updateEnd(@RequestBody RedirectQuery redirectQuery) {
        log.info("工作流完结 ： {}", JSON.toJSONString(redirectQuery));
        CarApplyVO bean = JSON.parseObject(redirectQuery.getFormVariables(), CarApplyVO.class);
        ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), carApplyService, "auditFinish", CarApplyVO.class, bean);
        return Response.success();
    }

    @Override
    @ApiOperation("作废时的修改方法, 非前端接口")
    public Response<Object> updateCancel(@RequestBody RedirectQuery redirectQuery) {
        log.info("updateCancel = {}", JSON.toJSONString(redirectQuery));
        String dataId = redirectQuery.getDataId();
        ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), carApplyService, "deleteById", Boolean.class, dataId);
        return Response.success();
    }

    /**
     * 自动过滤
     * 点击工作流提交的时候，业务需要编写此过滤器，返回过滤后的人员信息
     * @param submitterParam
     */
    @PostMapping("/{taskN}/submitter")
    public Response<List<WorkflowUser>> submitter(@PathVariable String taskN, @RequestBody SubmitterParam submitterParam) {
        log.info("用车申请审批设置审批人入参: {}", JSON.toJSONString(submitterParam));
        List<WorkflowUser> users = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), filter, taskN + "Submitter", List.class, submitterParam);
        return Response.ok(users);
    }

    /**
     * 选人组件过滤
     * 点击选人组件时，业务需要编写此过滤器，返回过滤后的人员信息
     *
     * @param submitterParam
     */
    @PostMapping("/{taskN}/handler")
    public Response<List<WorkflowUser>> handler(@PathVariable String taskN, @RequestBody SubmitterParam submitterParam) {
        log.info("用车申请审批选人组件过滤入参: {}", JSON.toJSONString(submitterParam));
        List<WorkflowUser> users = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), filter, taskN + "Handler", List.class, submitterParam);
        return Response.ok(users);
    }

    /**
     * 根据车辆申请id和当前登录用户查询申请记录
     * @param applyId
     * @return
     */
    @GetMapping("/getDrivingRecord")
    @ApiOperation("根据车辆申请id和当前登录用户查询申请记录")
    public Response<DriverRecord> getDrivingRecord(String applyId){
        log.info("车辆申请id， applyId = {}", applyId);
        DriverRecord drivingRecord = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), carApplyService, "getDrivingRecord", DriverRecord.class, applyId);
        return Response.ok(drivingRecord);
    }
}
